import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import LoginLayout from '@/layouts/LoginLayout.vue'
import { useMainStore } from '@/store/useMainStore'
import { getAuthRoutes } from '@/shared/auth'
import fullRoutes from '@/router/routes'
import login2 from '@/services/user/login2'
import { message } from 'ant-design-vue'
import { useSessionStorage } from '@vueuse/core'
import { StorageEnum } from '@/core/enums/shared'
import userInfo from '@/services/user/userInfo'
import { versionCheck } from '@/utils/versionCheck'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    meta: { title: '易百搜（品专）' },
    component: LoginLayout
  },
  {
    path: '/403',
    name: '403',
    meta: {
      title: '403',
      hidden: true
    },
    component: () => import('@/views/error/403.vue')
  },
  {
    path: '/geo-submit/:orderId',
    name: 'geo-submit',
    meta: {
      title: 'geo-submit',
      hidden: true
    },
    component: () => import('@/views/order/PlaceOrderView.vue')
  },
  {
    path: '/aireport/:orderId',
    name: 'aireport',
    meta: {
      title: '易抖优化',
      hidden: true
    },
    component: () => import('@/views/aireport/index.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const whiteList = ['login', 'geo-submit', 'aireport']
let urlParams: URLSearchParams | undefined = new URLSearchParams(location.search)

router.beforeEach(async (to, from, next) => {
  // await versionCheck()
  const mainStore = useMainStore()
  const token = urlParams?.get('token')
  const userId = urlParams?.get('userId')
  const reloadTag = useSessionStorage<string | null>(StorageEnum.ReloadTag, null)

  if (token && userId) {
    const [, fetchLogin2] = login2()
    await fetchLogin2({
      token: encodeURI(token),
      userId: Number(userId)
    })
    // 清空所有url参数记录，防止beforeEach下次循环时在此判断进入此方法
    urlParams = undefined
    document.location.search = ''
    // URL参数登录成功后，直接跳转到默认页面
    next('/price-package-df')
    return
  }

  if (!whiteList.includes(to.name as string) && reloadTag.value === '1') {
    message.warn('您的登录状态已过期，请重新登录')
    reloadTag.value = null
  }

  if (whiteList.includes(to.name as string) || whiteList.some((p) => to.path.startsWith(p))) {
    if (mainStore.token && mainStore.userInfo) {
      next(from.path || '/')
    } else {
      next()
    }
  } else {
    if (mainStore.token) {
      if (mainStore.userInfo) {
        if (mainStore.registerRouteFresh) {
          const authRoutes = getAuthRoutes(fullRoutes)
          router.addRoute(authRoutes)
          next({ ...to, replace: true })
          mainStore.setRegisterRouteFresh(false)
        } else {
          next()
        }
      } else {
        const [, fetchUserInfo] = userInfo()
        const [err, res] = await fetchUserInfo()

        if (err) {
          message.error(err.message)
          mainStore.removeToken()
          next(to.path || '/')
        } else if (!res.data.data) {
          message.error('请求出现错误')
          mainStore.removeToken()
          next(to.path || '/')
        } else {
          next(to.path || '/')
        }
      }
    } else {
      next('/login')
    }
  }
})

export default router
//
